import os

from flask import render_template, request, send_file
from werkzeug.utils import secure_filename

from fileconfig import FileConfigPath

# 允许上传的文件类型
ALLOWED_EXTENSIONS = {'json', 'docx'}


# 检查文件扩展名是否允许
def allowed_file(filename):
    return '.' in filename and \
        filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


def getFilePath(fileType):
    if fileType == 'CommandConfig':
        return FileConfigPath.command_params_path
    elif fileType == 'DocxConfig':
        return FileConfigPath.docx_template_path
    elif fileType == 'FixedConfig':
        return FileConfigPath.fixed_params_path
    elif fileType == 'AIConfig':
        return FileConfigPath.ai_params_path
    elif fileType == 'CityConfig':
        return FileConfigPath.city_params_path
    else:
        return None


# 定义一个视图函数
def paramsConfig(result=None):
    return render_template('paramsConfig.html', result=result)


def uploadFiles():
    if request.method == 'POST':
        # 检查是否有文件上传
        if 'file' not in request.files:
            return paramsConfig("No file part")
        filetype = request.form['type']
        uploadFolder = getFilePath(filetype)
        file = request.files['file']
        # 检查文件是否为空
        if file.filename == '':
            return paramsConfig("No selected file")
        # 检查文件类型是否允许
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(uploadFolder, filename))
            return paramsConfig("File uploaded successfully")
        else:
            return paramsConfig("File type not allowed")
    return paramsConfig("")


def downloadFile(fileType, fileName):
    filePath = getFilePath(fileType)
    return send_file(os.path.join(filePath, fileName), as_attachment=True)
